package com.kqb.sgai.service.impl;

import com.kqb.sgai.model.document.Msg;
import com.kqb.sgai.repository.MsgRepository;
import com.kqb.sgai.service.MsgService;
import jakarta.annotation.Resource;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author 杉果树皮
 */
@Service
public class MsgServiceImpl implements MsgService {

    @Resource
    private MsgRepository msgRepository;

    @Resource
    private MongoTemplate mongoTemplate;


    @Override
    public void saveMsg(List<Msg> msgs) {
        List<Msg> res = msgRepository.saveAll(msgs);
    }

    @Override
    public List<Msg> findByConversationId(String conversationId, int lastN) {
        // 创建查询条件
        Query query = new Query(Criteria.where("conversationId").is(conversationId));

        // 按时间降序排序（假设有date字段）
        query.with(Sort.by(Sort.Direction.DESC, "date"));

        // 限制返回结果数量
        query.limit(lastN);

        // 执行查询
        return mongoTemplate.find(query, Msg.class);

    }

    @Override
    public void deleteByConversationId(String conversationId) {
        Query query = new Query(Criteria.where("conversationId").is(conversationId));
        mongoTemplate.remove(query, Msg.class);
    }
}
